const axios = require('axios');
const usersModel = require('../../model/usersModel')
const jwt = require('jsonwebtoken');

module.exports.wxLogin = async (req, res, next) => {
    const params = req.body
    //微信小程序ID 与 秘钥
    // let appId = 'wxcf21745e3b5835bf'
    // let appSecret = "5f0c71e52138053dec62b7d8c55f0e3d"
    let data
    try {
        data = await axios({
            url: 'https://api.weixin.qq.com/sns/jscode2session',
            method: 'GET',
            params: {
                appId:params.appId,
                secret: params.appSecret,
                js_code: params.code,
                grant_type: 'authorization_code'
            }
        })

    } catch (error) {
        console.log('============== wxLogin 异常 ==============');
        console.log(error);
        console.log('=========================================');
        res.send({ code: 202, msg: '授权登录失败' });
        return false;

    }
    let openid = data.data.openid
    let session_key = data.data.session_key

    let user
    if (openid) {
        // console.log('openid',openid);
        try {
            [user] = await usersModel.find({ openid }, 'nickname phone avatar');
        } catch (error) {
            res.send({ code: 202, msg: '查询用户出错' });
        }
        // console.log('find',user);

        if (user) {
            // console.log('更新信息');
            //更新信息
            try {
                await usersModel.updateOne({ openid }, {
                    nickname: params.userInfo.nickName,
                    avatar: params.userInfo.avatarUrl,
                    sex: params.userInfo.gender
                });
            } catch (error) {
                res.send({ code: 202, msg: '更新用户信息出错' });
            }

        } else {
            //新增用户
            // console.log('新增用户');
            try {
                user = await usersModel.create({
                    openid,
                    nickname: params.userInfo.nickName,
                    avatar: params.userInfo.avatarUrl,
                    sex: params.userInfo.gender
                });
            } catch (error) {
                res.send({ code: 202, msg: '新增用户出错' });
            }

        }

        const token = jwt.sign({
            openid,
            _id: user._id,
            session_key
        }, 'PRIVATE_KEY', { expiresIn: '24h' });
        user.nickname = params.userInfo.nickName
        user.avatar = params.userInfo.avatarUrl
        res.send({ token: 'Bearer ' + token, user, code: 200, msg: '授权登录成功' });

    }




}

module.exports.getUserInfo = async (req, res, next) => {
    const params = req.body.token
    try {
        if (params) {
            const token = params.split(' ')[1];
            if (token) {
                const { _id } = jwt.verify(token, "PRIVATE_KEY");
                let user = await usersModel.find({ _id }, 'nickname phone avatar');
                // console.log('token');
                // console.log(user);
                res.send({
                    code: 200,
                    user: user[0],
                    message: '获取用户信息成功'
                })
            } else {
                res.send({
                    code: 202,
                    message: '用户信息获取失败，token 已失效'
                })
            }
        }

    } catch (error) {
        res.send({
            code: 202,
            message: '用户信息获取失败，token 已失效'
        })
    }
}